package top.chukongxiang.monitorservice.javafx.fxml;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import top.chukongxiang.monitorservice.javafx.core.FxContextHolder;
import top.chukongxiang.monitorservice.mapper.ServerConfigMapper;
import top.chukongxiang.monitorservice.model.constant.RegxConst;
import top.chukongxiang.monitorservice.model.entity.ServerConfig;
import top.chukongxiang.monitorservice.model.enums.SdkLoginMode;
import top.chukongxiang.monitorservice.model.exception.FxException;
import top.chukongxiang.monitorservice.service.HcNetSdkService;
import top.chukongxiang.monitorservice.tools.AlertUtil;
import top.chukongxiang.monitorservice.tools.FxBeanUtil;
import top.chukongxiang.monitorservice.tools.FxUtil;
import top.chukongxiang.monitorservice.tools.H2Util;

import java.io.IOException;

/**
 * @author 楚孔响
 * @version 1.0
 * @date 2023/10/26 10:54
 */
public class EditServerGui {

    public static final String KEY = "edit-server";

    @FXML
    public TextField deviceNameTextField;

    @FXML
    public TextField ipTextField;

    @FXML
    public TextField portTextField;

    @FXML
    public TextField usernameTextField;

    @FXML
    public PasswordField pwdPasswordField;

    @FXML
    public ToggleGroup sdkLoginModeGroup;

    public static boolean isAdd = true;

    public static void show() {
        show(null);
    }

    public static void show(ServerConfig serverConfig) {
        Platform.runLater(() -> {
            try {
                Stage stage = FxContextHolder.get(KEY);
                if (stage == null) {
                    stage = new Stage();
                    FXMLLoader fxmlLoader = new FXMLLoader(SettingGui.class.getClassLoader().getResource("fxml/edit-server.fxml"));
                    Parent pane = fxmlLoader.load();
                    Scene scene = new Scene(pane);
                    // 使用系统风格窗口，标题栏
                    stage.initStyle(StageStyle.DECORATED);
                    Stage serversState = FxContextHolder.get(ServersGui.KEY);
                    if (serversState != null) {
                        stage.initOwner(serversState);
                        stage.initModality(Modality.WINDOW_MODAL);
                    }
                    stage.setScene(scene);
                    FxContextHolder.set(KEY, stage, fxmlLoader.getNamespace());
                }
                if (serverConfig == null || serverConfig.getId() == null) {
                    isAdd = true;
                    stage.setTitle("新增设备");
                    updateUi(new ServerConfig());
                } else {
                    isAdd = false;
                    stage.setTitle("修改设备");
                    updateUi(serverConfig);
                }
                stage.show();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void testConnectAction(ActionEvent event) {
        assetForm();
        try {
            ServerConfig serverConfig = getSystemConfig(new ServerConfig());
            HcNetSdkService hcNetSdkService = FxBeanUtil.getHcNetSdkService();
            hcNetSdkService.loginV40(serverConfig, false);
            AlertUtil.info(FxContextHolder.get(KEY), "连接成功");
        } catch (Exception e) {
            AlertUtil.error(FxContextHolder.get(KEY), "连接失败", e);
        }
    }
    public void saveAction(ActionEvent event) {
        assetForm();
        ServerConfig systemConfig = getSystemConfig(new ServerConfig());
        H2Util.execute(ServerConfigMapper.class, serverConfigMapper -> {
            if (isAdd) {
                if (systemConfig.getId() == null) {
                    long id = IdUtil.getSnowflake().nextId();
                    systemConfig.setId(id);
                }
                serverConfigMapper.insert(systemConfig);
            } else {
                serverConfigMapper.updateById(systemConfig);
            }
        });
        // 更新
        ServersGui.loadData();
        closeAction(event);
    }
    public void closeAction(ActionEvent event) {
        Stage stage = FxContextHolder.get(KEY);
        stage.close();
    }

    private static void assetForm() {
        TextField deviceNameTextField = FxContextHolder.getNode(KEY, "deviceNameTextField");
        if (deviceNameTextField == null || StrUtil.isBlank(deviceNameTextField.getText())) {
            throw new FxException("设备名称必填");
        }

        TextField ipTextField = FxContextHolder.getNode(KEY, "ipTextField");
        if (ipTextField == null || !ReUtil.isMatch(RegxConst.IPV4, ipTextField.getText())) {
            throw new FxException("IP地址格式错误");
        }

        TextField portTextField = FxContextHolder.getNode(KEY, "portTextField");
        if (portTextField == null || !ReUtil.isMatch(RegxConst.PORT, portTextField.getText())) {
            throw new FxException("端口号格式错误");
        }

        TextField usernameTextField = FxContextHolder.getNode(KEY, "usernameTextField");
        if (usernameTextField == null || StrUtil.isBlank(usernameTextField.getText())) {
            throw new FxException("用户名不能为空");
        }

        TextField pwdPasswordField = FxContextHolder.getNode(KEY, "pwdPasswordField");
        if (pwdPasswordField == null || StrUtil.isBlank(pwdPasswordField.getText())) {
            throw new FxException("密码不能为空");
        }

        ToggleGroup sdkLoginModeGroup = FxContextHolder.getToggleGroup(KEY, "sdkLoginModeGroup");
        if (sdkLoginModeGroup == null || sdkLoginModeGroup.getSelectedToggle() == null) {
            throw new FxException("登录方式必填");
        }
    }

    private static ServerConfig getSystemConfig(ServerConfig serverConfig) {
        if (serverConfig == null) {
            serverConfig = new ServerConfig();
        }
        TextField deviceNameTextField = FxContextHolder.getNode(KEY, "deviceNameTextField");
        TextField ipTextField = FxContextHolder.getNode(KEY, "ipTextField");
        TextField portTextField = FxContextHolder.getNode(KEY, "portTextField");
        TextField usernameTextField = FxContextHolder.getNode(KEY, "usernameTextField");
        TextField pwdPasswordField = FxContextHolder.getNode(KEY, "pwdPasswordField");
        ToggleGroup sdkLoginModeGroup = FxContextHolder.getToggleGroup(KEY, "sdkLoginModeGroup");

        serverConfig.setName(deviceNameTextField.getText());

        String ip = ipTextField.getText();
        serverConfig.setIp(ip);

        String portStr = portTextField.getText();
        int port = Integer.parseInt(portStr);
        serverConfig.setPort(port);

        String username = usernameTextField.getText();
        serverConfig.setUsername(username);

        String pwd = pwdPasswordField.getText();
        serverConfig.setPassword(pwd);

        String sdkLoginModeGroupLabel = (String) sdkLoginModeGroup.getSelectedToggle().getUserData();
        SdkLoginMode sdkLoginMode = SdkLoginMode.valueOf(sdkLoginModeGroupLabel);
        serverConfig.setLoginMode(sdkLoginMode);

        return serverConfig;
    }

    private static void updateUi(ServerConfig serverConfig) {
        TextField deviceNameTextField = FxContextHolder.getNode(KEY, "deviceNameTextField");
        deviceNameTextField.setText(serverConfig.getName());

        TextField ipTextField = FxContextHolder.getNode(KEY, "ipTextField");
        ipTextField.setText(serverConfig.getIp());

        TextField portTextField = FxContextHolder.getNode(KEY, "portTextField");
        portTextField.setText(StrUtil.toStringOrNull(serverConfig.getPort()));

        TextField usernameTextField = FxContextHolder.getNode(KEY, "usernameTextField");
        usernameTextField.setText(serverConfig.getUsername());

        TextField pwdPasswordField = FxContextHolder.getNode(KEY, "pwdPasswordField");
        pwdPasswordField.setText(serverConfig.getPassword());

        ToggleGroup sdkLoginModeGroup = FxContextHolder.getToggleGroup(KEY, "sdkLoginModeGroup");
        Toggle loginModeToggle = serverConfig.getLoginMode() == null ? null :
                FxUtil.getToggleByUserData(sdkLoginModeGroup, serverConfig.getLoginMode().name());
        sdkLoginModeGroup.selectToggle(loginModeToggle);
    }



}
